import {getOpenId, setCorpCode, setOpenId, setToken} from "../../utils/auth";
import {systemAuthWxLogin, wxWxAuthCodeToOpenid} from "../../api";
import {showLoading} from "../../utils/jk-utils";
import {appId} from "../../utils/env";

export default {
	data() {
		return {
			showPopup: false,
			wxCode: '',
		}
	},
	methods: {
		getWxOpenId() {
			if (!this.wxCode && appId) return;
			return wxWxAuthCodeToOpenid({
				code: this.wxCode,
				appId: appId
			}).then(res => {
				if (res.data.status === 200) {
					setOpenId(res.data.res.openId);
				}
			});
		},
		getWxCode() {
			return new Promise((resolve, reject) => {
				let _this = this;
				wx.login({
					success (res) {
						_this.wxCode = res.code;
						resolve(res.code);
					},
					fail(res) {
						reject(res);
					}
				});
			})
		},
		// 根据openId获取登录态
		getAuthTokenByOpenId() {
			return systemAuthWxLogin({
				openId: getOpenId()
			}).then(res => {
				if (res.data.status === 200) {
					if (res.data.res) {
						setCorpCode(res.data.res.tenantId);
						setToken(`Bearer ${res.data.res.accessToken}`);
						uni.switchTab({
							url: '/pages/index/index'
						})
					} else {
						wx.showModal({
							title: '提示',
							content: '首次登录需输入账号信息，后续微信授权即可免密登录',
							showCancel: false,
							confirmText: '关闭',
							success: function(res) {
								if (res.confirm) {
								} else if (res.cancel) {
								}
							}
						});
					}
				}
			})
		},
		handleOpenPrivacyContract() {
			// 打开隐私协议页面
			wx.openPrivacyContract({
				success: () => {}, // 打开成功
				fail: () => {}, // 打开失败
				complete: () => {}
			})
		},
		showAuthTips() {
			this.showPopup = true;
		},
		// 自动登录
		async autoLogin() {
			showLoading(true, '正在授权...');
			// 判断缓存是否存在openId
			if (!getOpenId()) {
				// 获取code临时凭证
				if (!this.wxCode) await this.getWxCode();
				// 获取openId
				await this.getWxOpenId();
			}
			if (getOpenId()) await this.getAuthTokenByOpenId();
			showLoading(false);
		},
	}
}
